package com.example.his.api.front.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.front.form.SearchGoodsByIdForm;
import com.example.his.api.front.form.SearchGoodsListByPageForm;
import com.example.his.api.front.form.SearchIndexGoodsByPartForm;
import com.example.his.api.front.service.GoodsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController ( "FrontGoodsController" )
@RequestMapping ( "/front/goods" )
public class GoodsController {

  @Resource
  private GoodsService goodsService;

  /**
   * 根据商品ID查询商品详情
   *
   * @param form 包含商品ID的表单对象，ID不能为空且不能小于1
   * @return 返回包含商品信息的结果集
   */
  @PostMapping ( "/searchById" )
  public R searchById( @Valid @RequestBody SearchGoodsByIdForm form ) {
    // 调用服务层方法，根据ID查询商品信息
    HashMap map = goodsService.searchById( form.getId() );
    // 将查询结果封装到统一响应对象中并返回
    return R.ok().put( "result", map );
  }

  // 查询商品信息
  @PostMapping ( "/searchIndexGoodsByPart" )
  public R searchIndexGoodsByPart( @Valid @RequestBody SearchIndexGoodsByPartForm form ) {
    HashMap map = goodsService.searchIndexGoodsByPart( form.getPartIds() );
    return R.ok().put( "result", map );
  }

  /**
   * 分页查询商品列表
   *
   * @param form 包含查询条件的表单对象，如关键字、类型、性别、价格类型、排序类型、页码和每页记录数
   * @return 返回分页查询结果，包括总记录数、每页记录数、总页数、当前页数和分页数据
   */
  @PostMapping ( "/searchListByPage" )
  public R searchListByPage( @Valid @RequestBody SearchGoodsListByPageForm form ) {
    // 获取当前页码和每页记录数
    int page = form.getPage();
    int length = form.getLength();
    // 计算起始记录位置
    int start = ( page - 1 ) * length;
    // 将表单对象转换为Map，并添加起始位置参数
    Map param = BeanUtil.beanToMap( form );
    param.put( "start", start );
    // 调用服务层方法进行分页查询
    PageUtils pageUtils = goodsService.searchListByPage( param );
    // 将分页查询结果封装到统一响应对象中并返回
    return R.ok().put( "page", pageUtils );
  }

}
